<template>
  <div class="details_box">
    <div style="width: 100%; height: 40px; margin-bottom: 10px;">
      <el-button type="warning" style="float: right; margin-top: 10px;" @click="reback()">返回</el-button>
    </div>
    <div style="margin-bottom: 16px;">
      <el-button type="warning" icon="el-icon-edit" @click="openEditInputParam()">编辑参数</el-button>
      <!-- <el-button type="warning" icon="el-icon-edit" @click="openEditApplication()">编辑应用</el-button> -->
      <el-button type="primary" icon="el-icon-plus" @click="openSampleFileDatatDialog()">上传文件</el-button>
    </div>
    <div class="elTabs_height">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
        <el-tab-pane label="样本详情" name="first" class="el_tab_fourth">
          <el-form ref="form" label-width="100px">
            <el-form-item label="用户名：">
              <h3> {{ form_name }}</h3>
            </el-form-item>
            <el-form-item label="手机号：">
              <h3>{{ form_phone ? form_phone : "暂无数据" }}</h3>
            </el-form-item>
            <el-form-item label="样本编号：">
              <h3>{{ form_number }}</h3>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 问卷信息 -->
        <el-tab-pane label="问卷信息" name="second" class="el_tab_fourth">
          <el-descriptions title="" :column="1">
            <el-descriptions-item v-if="answerJsonList.length > 0" :key="item.key" v-for="item in answerJsonList"
              :label="item.key">
              <h3>{{ item.val }}</h3>
            </el-descriptions-item>

            <el-descriptions-item v-if="answerJsonList.length == 0" class="el-descriptions-item">
              <h3>暂无数据</h3>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <!-- 样本数据 -->
        <el-tab-pane label="样本数据" name="third" class="el_tab_fourth">
          <el-table v-loading="loading" :data="spamleData" border style="width: 50%">
            <el-table-column prop="type" label="数据类型">
              <template slot-scope="scope">
                <span v-if="scope.row.type == 'OUTPUT'">输出文件</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="small" @click="viewSapmle(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 文件信息 -->
        <el-tab-pane label="文件信息" name="fourth" class="el_tab_fourth">
          <el-table v-loading="loading" :data="spamleFileTreeData" row-key="name" style="width: 70%"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" highlight-current-row border>
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="文件名称" prop="name" min-width="200" />
            <el-table-column fixed="right" label="操作" min-width="480" width="480">
              <template #default="scope">
                <el-button type="primary" size="small" icon="el-icon-view" v-if="scope.row.file"
                  @click="fileView(scope.row.path)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 编辑参数 -->
    <el-dialog width="600px" :visible.sync="editInputParamDialogVisiable" title="编辑样本流程参数">
      <el-radio v-model="sysGene" label="true">使用系统参数</el-radio>
      <el-radio v-model="sysGene" label="false">使用自定义参数</el-radio>
      <codemirror style="margin-top: 10px;" v-if="sysGene == 'false'" class="runArgsContent" ref="codemirrorRetEdit"
        v-model="processInputParamJson" :options="cmOptions" />
      <el-button style="margin-top: 5px; margin-bottom: 5px; float: right; margin-left: 12px;"
        @click="editInputParamDialogVisiable = false">取消</el-button>
      <el-button type="primary" style="margin-top: 5px; margin-bottom: 5px; float: right; margin-left: 10px;"
        @click="updateProcessInput">保 存</el-button>
    </el-dialog>

    <!-- 编辑应用 -->
    <el-dialog :visible.sync="editDialog" title="编辑所属应用" width="400px">
      <el-form ref="userFormRef" :model="formData" label-width="100px">
        <el-form-item label="所属应用" prop="dfApplicationId">
          <el-select v-model="formData.dfApplicationId" @change="changeApplication">
            <el-option v-for="field in applicationList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属关联模板" prop="reportTemplateId" style="margin-top: 5%;">
          <el-select v-model="formData.reportTemplateId">
            <el-option v-for="field in appTemplateList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveApplication">确 定</el-button>
          <el-button @click="editDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看文件 -->
    <el-dialog :visible.sync="viewFileVisible" title="上传报告文件" width="750px" :close-on-click-modal="false">
      <div class="viewFileVisible_box">
        <div class="output_file">
          <div class="input_file_top">
            <h3>输出文件</h3>
            <el-upload class="upload-dialog" ref="upload" :action="out_uploadAction" :show-file-list="false"
              :on-change="submitUpload_out" :on-success="uploadFileSuccess_out" :headers="headers" :auto-upload="false">
              <el-button slot="trigger" style="margin-left: 5px" type="success">上传输出文件（zip）</el-button>
              <div slot="tip" class="el-upload__tip"></div>
            </el-upload>
          </div>
          <el-table :data="outputFileData" border style="width: 100%" max-height="500">
            <el-table-column prop="path" label="文件路径"></el-table-column>
            <el-table-column prop="suffix" label="文件类型"></el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 样本数据，查看 -->
    <el-dialog :visible.sync="viewSampleVisible" title="样本数据" width="850px">
      <el-table :data="dataJsonList" border style="width: 100%">
        <el-table-column prop="key" label="key"></el-table-column>
        <el-table-column prop="val" label="值">
          <template slot-scope="scope">
            <span>{{ JSON.stringify(scope.row.val) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 文件信息,查看 -->
    <el-dialog :visible.sync="fileViewVisible" title="文件信息" width="950px">
      <template v-if="!fileImgData">
        <div v-html="fileData" style="font-size: 16px;"></div>
      </template>
      <template v-else>
        <img :src="fileData" height="360px" width="100%" />
      </template>
    </el-dialog>

  </div>
</template>

<script>
import reportTemplateApi from '@/api/report/template'
import dfApplicationApi from '@/api/analysis/application';
import reportSampleApi from '@/api/report/reportSample';
import seqSampleApi from '@/api/sequence/seqSample';
// import { Session } from '@/utils/storage';

import { codemirror } from 'vue-codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/javascript/javascript.js';
import "codemirror/mode/markdown/markdown.js";
import 'codemirror/mode/css/css.js';
import 'codemirror/mode/vue/vue.js';
import '../setting';
export default {
  name: '',
  props: {
    viewDetailsDataPro: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      form_name: "",
      form_phone: "",
      form_number: "",
      activeName: 'first',
      editInputParamDialogVisiable: false,
      processInputParamJson: "",
      sysGene: 'true',
      cmOptions: {
        tabSize: 2, // tab
        styleActiveLine: true,
        lineNumbers: true, // 换行操作
        lineWrapping: true, // 换行操作
        styleSelectedText: true,
        line: true,
        foldGutter: true,
        gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
        highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
        mode: 'application/json',
        hintOptions: {
          completeSingle: false,
        },
        keyMap: 'sublime',
        matchBrackets: true,
        showCursorWhenSelecting: true,
        theme: 'monokai',
        // theme: 'solarized',
        extraKeys: {},
      },
      editDialog: false,
      applicationList: [],
      appTemplateList: [],
      formData: {},

      checkedSample: {},
      viewFileVisible: false,
      out_uploadAction: '',
      headers: {},
      outputFileData: [],
      viewFileSampleId: '',

      answerJsonList: [],
      spamleFileTreeData: [],
      loading: false,

      spamleData: [],
      dataJsonList: [],
      viewSampleVisible: false,
      fileData: '',
      fileImgData: false,
      fileViewVisible: false

    }
  },
  created() {
    // console.log(this.viewDetailsDataPro);
    this.form_name = this.viewDetailsDataPro.userName;
    this.form_phone = this.viewDetailsDataPro.phone;
    this.form_number = this.viewDetailsDataPro.number;
  },
  mounted() {
    this.headers = {
      Authorization: 'Bearer ' + localStorage.getItem('token'),
    };

  },
  methods: {
    // 返回
    reback() {
      this.$emit("close");
    },
    // 文件信息查看
    fileView(path) {
      let that = this;
      this.fileViewVisible = true;
      reportSampleApi.getFileStreamData(this.viewDetailsDataPro.id, encodeURI(path)).then((res) => {
        let data = res;
        this.fileData = '000'
        if (path.indexOf('.png') != -1) {
          const binaryData = [];
          binaryData.push(res);
          data = window.URL.createObjectURL(data);
          this.fileImgData = true;
          this.fileData = data;
        } else {
          let reader = new FileReader();
          reader.readAsText(data);
          reader.onload = function (event) {
            that.fileImgData = false;
            let r = event.target.result;
            r = r.replace('\n', '<br />')
            that.fileData = r;
          }
        }

      })
    },
    // 样本数据 查看
    viewSapmle(row) {
      this.viewSampleVisible = true;
      let dataJson = row.dataJson;
      dataJson = JSON.parse(dataJson);
      let dataJsonList = [];
      for (let k in dataJson) {
        dataJsonList.push({
          key: k,
          val: dataJson[k]
        })
      }
      if (dataJsonList == null || dataJsonList == "{}") {
        this.dataJsonList = [];
      } else {
        this.dataJsonList = dataJsonList;
      }
      console.log(this.dataJsonList);

    },
    handleClick(tab, event) {
      this.activeName = tab.name;
      // 问卷信息
      if (this.activeName == "second") {
        let answerJson = this.viewDetailsDataPro.answerJson;
        if (answerJson) {
          answerJson = JSON.parse(answerJson)
          // console.log(answerJson)
          let answerJsonList = []
          for (let k in answerJson) {
            answerJsonList.push({
              key: k,
              val: answerJson[k]
            })
          }

          if (answerJsonList == null || answerJsonList == "{}") {
            this.answerJsonList = [];
          } else {
            this.answerJsonList = answerJsonList;
          }
          // console.log(this.answerJsonList)
        }
      }
      // 样本数据
      if (this.activeName == "third") {
        this.loading = true;
        reportSampleApi.getSampleData(this.viewDetailsDataPro.id).then((res) => {
          this.loading = false;
          if (res.code == 200) {
            this.spamleData = res.data;
          } else {
            this.$message.error(res.msg);
          }
        }).catch((error) => { this.loading = false; });
      }
      if (this.activeName == "fourth") {
        this.loading = true;
        reportSampleApi.getSampleFileTree(this.viewDetailsDataPro.id).then((res) => {
          this.loading = false;
          if (res.code == 200) {
            this.spamleFileTreeData = res.data;
          } else {
            this.$message.error(res.msg);
          }
        }).catch((error) => { this.loading = false; });
      }
    },
    // 编辑参数
    openEditInputParam() {
      this.editInputParamDialogVisiable = true;
      seqSampleApi.get(this.viewDetailsDataPro.id).then(res => {
        this.processInputParamJson = res.data.processInputParamJson ? res.data.processInputParamJson : '';
      })
    },
    // 编辑参数，保存
    updateProcessInput() {
      reportSampleApi.updateInputParam({
        id: this.viewDetailsDataPro.id,
        processInputParamJson: this.processInputParamJson,
        sysGene: this.sysGene
      }).then(res => {
        this.$message({ message: '编辑参数成功！', type: 'success' });
        this.editInputParamDialogVisiable = false;
      })
    },

    // 编辑应用
    openEditApplication() {
      this.editDialog = true;
      dfApplicationApi.list().then(res => {
        this.applicationList = res.data;
        if (this.applicationList.length != 0) {
          reportTemplateApi.listByApplication(this.applicationList[0].id).then(r => {
            this.appTemplateList = r.data;
            this.formData = this.viewDetailsDataPro;
          })
        } else {
          this.formData = this.viewDetailsDataPro;
        }
      })
    },
    // 编辑应用，保存
    saveApplication() {
      reportSampleApi.setDfApplication(this.viewDetailsDataPro.id, this.formData.dfApplicationId, this.formData.reportTemplateId).then(res => {
        this.editDialog = false;
        this.$message({ message: '样本所属应用设置成功！', type: 'success' });
        // this.$emit("close");
        this.$parent.getReportSampleData(this.viewDetailsDataPro.activeSampleType);
      })
    },
    changeApplication(val) {
      this.appTemplateList = [];
      this.formData = {
        dfApplicationId: this.formData.dfApplicationId
      }
      reportTemplateApi.listByApplication(val).then(r => {
        this.appTemplateList = r.data;
        this.formData = row;
      })
    },

    // 上传文件
    openSampleFileDatatDialog() {
      // console.log(this.viewDetailsDataPro.id);
      reportSampleApi.existSampleData(this.viewDetailsDataPro.id).then(res => {
        let data = res.data;
        if (data) {
          this.$confirm('检测到此样本中已上传数据文件，是否重新上传?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.viewFileVisible = true;
            this.getFile();

            this.input_uploadAction = process.env.VUE_APP_FILE_API_PREV + '/service-platform/sample-file/upload/' + row.id + '?type=INPUT'; //输入文件
            this.out_uploadAction = process.env.VUE_APP_FILE_API_PREV + '/service-platform/sample-file/upload/' + row.id + '?type=OUTPUT'; // 输出文件 
          }).catch(() => { });
        } else {
          this.viewFileVisible = true;
          this.getFile();

          this.input_uploadAction = process.env.VUE_APP_FILE_API_PREV + '/service-platform/sample-file/upload/' + row.id + '?type=INPUT'; //输入文件
          this.out_uploadAction = process.env.VUE_APP_FILE_API_PREV + '/service-platform/sample-file/upload/' + row.id + '?type=OUTPUT'; // 输出文件
        }
      })
    },
    // 上传报告文件，输出文件
    getFile() {
      reportSampleApi.getFileList(this.viewDetailsDataPro.id).then((res) => {
        let fileData = res.data;
        let outOutData = [];
        let inputData = [];
        fileData.forEach((i) => {
          if (i.fileType == 'OUTPUT') {
            outOutData.push(i);
          }
          if (i.fileType == 'INPUT') {
            inputData.push(i);
          }
        });
        this.outputFileData = outOutData;
        this.inputFileData = inputData;
      });
    },

    submitUpload_out() {
      this.$refs.upload.submit();
    },
    uploadFileSuccess_out() {
      this.$message({ message: '文件上传成功！', type: 'success' });
      this.viewFileVisible = false;
    },


  },

}
</script>

<style scoped>
.details_box {
  width: 100%;
  padding: 0 1% 1% 1%;
  background-color: white;
}

.input_file_top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2%;
}

.el-descriptions-item__container .el-descriptions-item__label {
  display: none !important;
}

.elTabs_height {
  height: calc(100vh - 240px);
}

.el_tab_fourth {
  height: calc(100vh - 312px) !important;
  overflow-y: auto;
}

.el-form-item {
  margin-bottom: 0 !important;
}
</style>
